
#include <stdarg.h>
#include "FreeRTOS.h"
#include "queue.h"
#include "USART.h"
#include "fout.h"
#include "debug.h"
#include "macros.h"

xQueueHandle queue_fout;

typedef struct 
{
	unsigned char dev;
	char msg[OUTF_MSG_BUFFER_SIZE];
}fout_msg_t;

void fout_init ( void )
{
	queue_fout = xQueueCreate( 5, sizeof(fout_msg_t));
}


int fout(int dev, const char *frm, ... )
{
	fout_msg_t fmsg;

	char *m = fmsg.msg; 

	va_list args;

	//vTaskSuspendAll();	
	
//	taskENTER_CRITICAL();

	va_start( args, frm );
	
	print(&m,frm,args);
	fmsg.dev = dev;
	
	xQueueSend(queue_fout, &fmsg, portMAX_DELAY); //portMAX_DELAY
	//xQueueSend(queue_fout, &fmsg, (1000 MSEC)); //portMAX_DELAY

	va_end(args);
	//xTaskResumeAll();

//	taskEXIT_CRITICAL();
	
	
	return 0;
}


void fout_task ( void *pvParameters )
{
	fout_msg_t msg;
	
	/* unsigned portBASE_TYPE s =uxTaskGetStackHighWaterMark(NULL); */
	/* DBG("statck size: %d",s); //Dima */

	for( ;; )
	{
		xQueueReceive(queue_fout,&msg,portMAX_DELAY);

		switch( msg.dev )
		{  
			case FOUT_DEV_U0:
			case FOUT_DEV_U2:
			case FOUT_DEV_U3:
				putstr( msg.msg, msg.dev);
				if ( msg.dev == FOUT_DEV_U2 )
				{
					dbg(">> %s", msg.msg); //Dima
				}
			break;

			case FOUT_DEV_VCOM:
				vcom_putstr( msg.msg );
				break;
		}
	}
}
